package com.bdbit.ChargingStation.services.impl;

import com.alibaba.fastjson.JSONObject;
import com.bdbit.ChargingStation.controller.ChargingOrderController;
import com.bdbit.ChargingStation.entity.ChargingOrder;
import com.bdbit.ChargingStation.entity.OrderEntity;
import com.bdbit.ChargingStation.mapper.ChargingorderMapper;
import com.bdbit.ChargingStation.services.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.context.annotation.Lazy;
import lombok.extern.slf4j.Slf4j;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.dao.EmptyResultDataAccessException;

@Service("chargingMessageServiceImpl")
@Slf4j
public class ChargingMessageServiceImpl implements MqttMessageService {
    // 服务端消息标记
    private static final String SERVER_TAG = "[SERVER]";

    // 设备状态枚举
    enum DeviceStatus {
        UNKNOWN,             // 设备未初始化
        EXPECT_HEARTBEAT,    // 期望收到心跳（首次连接）
        EXPECT_SELF_CHECK,   // 期望收到自检结果
        CHARGING,            // 充电中状态
        FAULT                // 故障状态
    }

    private final ConcurrentHashMap<String, DeviceStatus> deviceStatusMap = new ConcurrentHashMap<>();
    
    // 支付确认超时检测
    private final ConcurrentHashMap<String, Long> paymentConfirmationMap = new ConcurrentHashMap<>();
    private final ScheduledExecutorService scheduler = new ScheduledThreadPoolExecutor(1);
    private static final long PAYMENT_CONFIRMATION_TIMEOUT = 40000; // 40秒超时
    @Autowired
    @Lazy
    private MqttServerService mqttServerService;
    @Autowired
    ChargingOrderService chargingOrderService;
    @Autowired
    ChargingOrderController chargingOrderController;
    @Autowired
    @Lazy
    private ChargingService chargingService;
    
    @Autowired
    private MqttMessageListener mqttMessageListener;

    @Autowired
    private JdbcTemplate jct;

    // 正则表达式匹配设备消息格式
    private static final Pattern FINE_PATTERN = Pattern.compile("^(\\d+)\\.fine$");
    private static final Pattern PAYMENT_PATTERN = Pattern.compile("^(\\d+)\\.(\\d{3})\\.(\\d{2})$");
    private static final Pattern HEARTBEAT_PATTERN = Pattern.compile("^\\d+$");
    private static final Pattern CHARING_PATTERN = Pattern.compile("^(\\d+)\\.charing\\.(\\d+)$");
    private static final Pattern OVERLOAD_PATTERN = Pattern.compile("^(\\d+)\\.overload$");
    private static final Pattern NOLOAD_PATTERN = Pattern.compile("^(\\d+)\\.NoLoad$");
    private static final Pattern CHANGED_PATTERN = Pattern.compile("^(\\d+)\\.changed$");
    private static final Pattern ERRORDONE_PATTERN = Pattern.compile("^(\\d+)\\.errordone$");
    private static final Pattern DONE_PATTERN = Pattern.compile("^(\\d+)\\.done$");

    // 命令到响应的映射
    private static final Map<String, String> COMMAND_RESPONSE = new HashMap<>();

    static {
        COMMAND_RESPONSE.put("fine", "开始放电");
        COMMAND_RESPONSE.put("overload", "充电异常已断电");
        COMMAND_RESPONSE.put("done", "已结束充电");
        COMMAND_RESPONSE.put("errordone", "暂停充电！请于60s内恢复充电");
        COMMAND_RESPONSE.put("changed", "停止供电！充电器功率过大！");
        COMMAND_RESPONSE.put("NoLoad", "没有插上充电器");
        COMMAND_RESPONSE.put("no load", "没有插上充电器");
    }

    // 设备状态缓存
    private final Map<String, DeviceState> deviceStates = new HashMap<>();

    // 设备配置（实际应从数据库加载）
    private final Map<String, DeviceConfig> deviceConfigs = new HashMap<>();

    {
        // 默认设备配置
        DeviceConfig config = new DeviceConfig();
        config.workMode = WorkMode.AMOUNT_BASED;
    }
    
    /**
     * 初始化方法，启动支付确认超时检测任务
     */
    @Autowired
    public void init() {
        // 每5秒检查一次支付确认超时
        scheduler.scheduleAtFixedRate(this::checkPaymentConfirmationTimeout, 5, 5, TimeUnit.SECONDS);
    }
    
    /**
     * 检查支付确认超时
     * 如果支付后40秒内没有收到charing消息，则触发退款
     */
    private void checkPaymentConfirmationTimeout() {
        long now = System.currentTimeMillis();
        paymentConfirmationMap.forEach((iccid, timestamp) -> {
            if (now - timestamp > PAYMENT_CONFIRMATION_TIMEOUT) {
                log.warn("支付确认超时: iccid={}, 已等待{}秒", iccid, (now - timestamp) / 1000);
                
                try {
                    // 获取关联订单
                    String orderId = findOrderIdByIccid(iccid);
                    if (orderId != null) {
                        // 构造超时事件请求 - 修复：确保包含device_id字段
                        JSONObject eventPayload = new JSONObject();
                        eventPayload.put("device_id", iccid);
                        eventPayload.put("reason", "payment_confirmation_timeout");
                        
                        // 处理退款
                        try {
                            mqttMessageListener.handlePowerOutageEvent(eventPayload.toJSONString());
                            log.info("处理支付确认超时退款: iccid={}, orderId={}", iccid, orderId);
                        } catch (Exception e) {
                            log.error("处理支付确认超时退款失败", e);
                        }
                    } else {
                        log.warn("支付确认超时但未找到关联订单: iccid={}", iccid);
                    }
                } catch (Exception e) {
                    log.error("支付确认超时处理异常: iccid={}", iccid, e);
                } finally {
                    // 移除超时记录
                    paymentConfirmationMap.remove(iccid);
                }
            }
        });
    }
    
    /**
     * 根据ICCID查找订单ID121
     */
    private String findOrderIdByIccid(String iccid) {
        try {
            // 直接调用chargingOrderService.getOrderIdByDevice方法
            return chargingOrderService.getOrderIdByDevice(iccid);
        } catch (Exception e) {
            log.error("根据ICCID查找订单失败: iccid={}", iccid, e);
            return null;
        }
    }

    @Override
    public String processMessage(String topic, String payload) {
        // 清理消息内容
        String cleanPayload = payload.replaceAll("[\r\n]", "").trim();
        log.info("处理MQTT消息 - 主题: {}, 内容: {}", topic, cleanPayload);

        // 关键修复1: 提前过滤服务端消息
        if (cleanPayload.startsWith(SERVER_TAG)) {
//            log.warn("忽略服务端发出的消息: {}", cleanPayload);
            return null; // 直接返回不处理
        }

        // 提取设备ICCID
        String iccid = extractIccid(topic, cleanPayload);

        // 初始化设备状态
        DeviceStatus status = deviceStatusMap.computeIfAbsent(
                iccid,
                k -> DeviceStatus.EXPECT_HEARTBEAT
        );
        log.debug("设备状态: {}", status);

        // 处理心跳包
        Matcher heartbeatMatcher = HEARTBEAT_PATTERN.matcher(cleanPayload);
        if (heartbeatMatcher.matches()) {
            log.info("收到心跳包 - ICCID: {}", cleanPayload);
            //更新心跳时间
            chargingOrderService.updateDeviceLastTime(cleanPayload);

            return handleHeartbeat(iccid);
        }

        // 处理断电指令
        if (cleanPayload.equals("power_off")) {
            String orderId = extractOrderIdFromPayload(payload);
            chargingService.handlePowerOff(orderId);
            return "已收到断电指令";
        }

        // 处理自检完成消息
        Matcher fineMatcher = FINE_PATTERN.matcher(cleanPayload);
        if (fineMatcher.matches()) {
            String extractedIccid = fineMatcher.group(1);
            log.info("充电桩 {} 自检完成", extractedIccid);
            return handleFineEvent(extractedIccid);
        }

        // 处理付款数据
        Matcher paymentMatcher = PAYMENT_PATTERN.matcher(cleanPayload);
        if (paymentMatcher.matches()) {
            String imei = paymentMatcher.group(1);
            String amountStr = paymentMatcher.group(2);
            String modeStr = paymentMatcher.group(3);
            log.info("收到付款数据 - IMEI: {}, 金额: {}, 模式: {}", imei, amountStr, modeStr);

            // 关键修改：改为异步处理
            handlePaymentDataAsync(imei, amountStr, modeStr);
            
            // 记录支付确认开始时间，用于超时检测
            String deviceIccid = findIccidByImei(imei);
            if (deviceIccid != null) {
                paymentConfirmationMap.put(deviceIccid, System.currentTimeMillis());
                log.info("开始支付确认超时检测: iccid={}", deviceIccid);
            }
            
            return "OK|支付处理中\r\n";
        }
        
        // 处理充电确认消息 (charing)
        Matcher charingMatcher = CHARING_PATTERN.matcher(cleanPayload);
        if (charingMatcher.matches()) {
            String extractedIccid = charingMatcher.group(1);
            String chargingSeconds = charingMatcher.group(2);
            log.info("收到充电确认消息 - ICCID: {}, 充电时长: {}秒", extractedIccid, chargingSeconds);
            
            // 移除支付确认超时检测
            paymentConfirmationMap.remove(extractedIccid);
            
            // 构造消息体
            JSONObject message = new JSONObject();
            message.put("device_id", extractedIccid);
            message.put("charging_seconds", Integer.parseInt(chargingSeconds));
            
            // 异步处理充电确认消息
            CompletableFuture.runAsync(() -> {
                mqttMessageListener.handleCharingMessage(message.toJSONString());
            });
            
            return "OK|已确认充电\r\n";
        }
        
        // 处理overload消息
        Matcher overloadMatcher = OVERLOAD_PATTERN.matcher(cleanPayload);
        if (overloadMatcher.matches()) {
            String extractedIccid = overloadMatcher.group(1);
            log.info("收到overload消息 - ICCID: {}", extractedIccid);
            
            // 移除支付确认超时检测
            paymentConfirmationMap.remove(extractedIccid);
            
            // 构造消息体
            JSONObject message = new JSONObject();
            message.put("device_id", extractedIccid);
            message.put("status", "overload");
            
            // 异步处理overload消息
            CompletableFuture.runAsync(() -> {
                mqttMessageListener.handleOverloadMessage(message.toJSONString());
            });
            
            return COMMAND_RESPONSE.get("overload") + "\r\n";
        }
        
        // 处理NoLoad消息
        Matcher noloadMatcher = NOLOAD_PATTERN.matcher(cleanPayload);
        if (noloadMatcher.matches()) {
            String extractedIccid = noloadMatcher.group(1);
            log.info("收到NoLoad消息 - ICCID: {}", extractedIccid);
            
            // 移除支付确认超时检测
            paymentConfirmationMap.remove(extractedIccid);
            
            // 构造消息体
            JSONObject message = new JSONObject();
            message.put("device_id", extractedIccid);
            message.put("status", "no load");
            
            // 异步处理NoLoad消息
            CompletableFuture.runAsync(() -> {
                mqttMessageListener.handleNoLoadMessage(message.toJSONString());
            });
            
            return COMMAND_RESPONSE.get("NoLoad") + "\r\n";
        }

        if(cleanPayload.contains("My ICCID is")){
            String imei = chargingOrderController.getDeviceImei(topic);
            mqttServerService.sendToDevice(imei,topic + "\r\n");
        }
        
        // 处理changed消息
        Matcher changedMatcher = CHANGED_PATTERN.matcher(cleanPayload);
        if (changedMatcher.matches()) {
            String extractedIccid = changedMatcher.group(1);
            log.info("收到changed消息 - ICCID: {}", extractedIccid);
            
            // 构造消息体
            JSONObject message = new JSONObject();
            message.put("device_id", extractedIccid);
            
            // 异步处理changed消息
            CompletableFuture.runAsync(() -> {
                mqttMessageListener.handleChangedMessage(message.toJSONString());
            });
            
            return COMMAND_RESPONSE.get("changed") + "\r\n";
        }
        
        // 处理errordone消息
        Matcher errordoneMatcher = ERRORDONE_PATTERN.matcher(cleanPayload);
        if (errordoneMatcher.matches()) {
            String extractedIccid = errordoneMatcher.group(1);
            log.info("收到errordone消息 - ICCID: {}", extractedIccid);
            
            // 构造消息体
            JSONObject message = new JSONObject();
            message.put("device_id", extractedIccid);
            
            // 异步处理errordone消息
            CompletableFuture.runAsync(() -> {
                mqttMessageListener.handleErrorDoneMessage(message.toJSONString());
            });
            
            return COMMAND_RESPONSE.get("errordone") + "\r\n";
        }
        
        // 处理done消息
        Matcher doneMatcher = DONE_PATTERN.matcher(cleanPayload);
        if (doneMatcher.matches()) {
            String extractedIccid = doneMatcher.group(1);
            log.info("收到done消息 - ICCID: {}", extractedIccid);
            
            // 构造消息体
            JSONObject message = new JSONObject();
            message.put("device_id", extractedIccid);
            
            // 异步处理done消息
            CompletableFuture.runAsync(() -> {
                mqttMessageListener.handleDoneMessage(extractedIccid);
            });
            
            return COMMAND_RESPONSE.get("done") + "\r\n";
        }
        
        // 处理no load消息（断电或充满）
        if ("no load".equalsIgnoreCase(cleanPayload) || "NoLoad".equalsIgnoreCase(cleanPayload)) {
            log.info("收到no load消息 - ICCID: {}", iccid);
            handleNoLoadMessageAsync(iccid);
            return COMMAND_RESPONSE.get(cleanPayload) + "\r\n";
        }

        // 处理预设命令
        if (COMMAND_RESPONSE.containsKey(cleanPayload)) {
            log.info("处理预设命令: {}", cleanPayload);
            return COMMAND_RESPONSE.get(cleanPayload) + "\r\n";
        }

        // 未识别的消息
        log.warn("未识别的消息: {}", cleanPayload);
        return "ERROR|未知命令\r\n";
    }

    private String extractOrderIdFromPayload(String payload) {
        return "ORDER_123456";
    }
    // 异步处理付款数据
    private void handlePaymentDataAsync(String imei, String amountStr, String modeStr) {
        CompletableFuture.runAsync(() -> {
            try {
                // 处理付款数据
                handlePaymentData(imei, amountStr, modeStr);
            } catch (Exception e) {
                log.error("处理付款数据失败", e);
            }
        });
    }
    /**
     * 处理充电桩自检完成事件
     */
    private String handleFineEvent(String iccid) {
        log.info("充电桩 {} 自检完成", iccid);
        
        // 更新设备状态为自检完成
        deviceStatusMap.put(iccid, DeviceStatus.EXPECT_HEARTBEAT);
        
        // 记录设备上线时间
        DeviceState state = getDeviceState(iccid);
        state.lastHeartbeatTime = System.currentTimeMillis();

        //查询有没有正在进行的订单，有的话根据时间退款
        String orderId = findOrderIdByIccid(iccid);
        if (orderId != null) {
            // 构造超时事件请求 - 修复：确保包含device_id字段
            JSONObject eventPayload = new JSONObject();
            eventPayload.put("device_id", iccid);
            eventPayload.put("reason", "duandiadn");

            // 处理退款
            try {
                mqttMessageListener.handlePowerOutageEvent(eventPayload.toJSONString());
                log.info("处理断电退款: iccid={}, orderId={}", iccid, orderId);
            } catch (Exception e) {
                log.error("处理断电退款失败1", e);
            }
        } else {
            log.warn("支付确认超时但未找到关联订单: iccid={}", iccid);
        }
        // 只返回确认消息，不生成付款指令
        return "OK|自检完成\r\n";
    }

    /**
     * 处理付款数据
     */
    private String handlePaymentData(String deviceId, String amountStr, String modeStr) {
        try {
            int timeParam = Integer.parseInt(amountStr);
            WorkMode workMode = "00".equals(modeStr) ? WorkMode.TIME_BASED : WorkMode.AMOUNT_BASED;
    
            // 直接使用deviceId作为eleCode，不再进行IMEI到ICCID的转换
            String eleCode = deviceId;
            
            // 验证eleCode是否有效（不是AUTO_开头的临时值）
            if (eleCode.startsWith("AUTO_")) {
                log.error("检测到无效的设备标识符: {}", eleCode);
                return "ERROR|无效的设备标识符\r\n";
            }
    
            // 根据工作模式计算充电时长
            int chargingMinutes = calculateChargingTime(workMode, timeParam);
            
            if (workMode == WorkMode.TIME_BASED) {
                double hours = timeParam / 10.0;
                log.info("充电桩 {} 将按时长充电 {} 小时（{}分钟）", eleCode, hours, chargingMinutes);
            } else {
                log.info("充电桩 {} 将按金额充电 {}分钟", eleCode, chargingMinutes);
            }
    
            // 检查是否已存在未完成的订单
            String existingOrderId = findOrderIdByDeviceId(eleCode);
            if (existingOrderId != null) {
                //更新全部订单为已完成
                log.warn("设备 {} 已存在未完成订单: {}，将状态更新了为异常完成", eleCode, existingOrderId);
                UpdateOrderIdByDeviceId(eleCode);

                //return "ERROR|设备正在充电中\r\n";
            }
    
            // 创建订单
            OrderEntity order = createOrder(eleCode, timeParam, chargingMinutes);
            chargingOrderService.save(order);
    
            return "OK|充电时长:" + chargingMinutes + "分钟\r\n";
        } catch (NumberFormatException e) {
            log.error("无效的参数格式: {}", amountStr);
            return "ERROR|无效参数\r\n";
        } catch (Exception e) {
            log.error("处理支付数据时发生错误", e);
            return "ERROR|系统错误\r\n";
        }
    }
    
    private String findOrderIdByDeviceId(String deviceId) {
        try {
            return chargingOrderService.getOrderIdByDevice(deviceId);
        } catch (Exception e) {
            log.debug("查询设备订单时发生异常: {}", e.getMessage());
            return null;
        }
    }

    private int UpdateOrderIdByDeviceId(String deviceId) {
        try {
            return chargingOrderService.UpdateOrderIdByDeviceId(deviceId);
        } catch (Exception e) {
            log.debug("更新设备订单时发生异常: {}", e.getMessage());
            return -1;
        }
    }

    private int calculateChargingTime(WorkMode workMode, int timeParam) {
        if (workMode == WorkMode.AMOUNT_BASED) {
            // 模式1：按金额充电 - 统一费率：1元 = 5分钟
            return (int) (timeParam / 100.0 * 5);
        } else {
            // 模式2：按时长充电 - 也统一按1元=5分钟的标准
            // timeParam是金额（分），转换为充电时长（分钟）
            return (int) (timeParam / 100.0 * 5);
        }
    }
    /**
     * 自动关联设备
     */
    // 删除或注释掉autoAssociateDevice方法，因为不再需要IMEI到ICCID的映射
    /*
    private String autoAssociateDevice(String imei) {
        // 这个方法不再需要，因为我们直接使用eleCode
    }
    */
    
    /**
     * 创建订单
     */
    private OrderEntity createOrder(String eleCode, int amountCents, int chargingMinutes) {
        OrderEntity order = new OrderEntity();

        // 将金额（分）转换为元
        BigDecimal totalAmount = BigDecimal.valueOf(amountCents).divide(BigDecimal.valueOf(100));
        order.setTotalAmount(totalAmount);

        // 设置实际支付金额为预付金额（因为已经支付）
        order.setPrepayAmount(totalAmount);
        
        // 设置单价（必填字段，默认为0）
        order.setUnitPrice(BigDecimal.ZERO);
        
        // 设置逻辑删除标志（0表示未删除）
        order.setIsDeleted(0);

        // 设置充电时长
        order.setReportedDuration(chargingMinutes);
        // 设置charging_minutes字段（通过反射设置，因为实体类可能没有这个方法）
        try {
            java.lang.reflect.Method method = OrderEntity.class.getMethod("setChargingMinutes", Integer.class);
            method.invoke(order, chargingMinutes);
        } catch (Exception e) {
            log.warn("无法设置充电分钟数: {}", e.getMessage());
        }

        // 获取当前时间
        Date now = new Date();

        // 设置订单基本信息
        order.setCreateDate(now);
        
        // 设置update_date字段（注意：这是Date类型，不是DateTime类型）
        Calendar cal = Calendar.getInstance();
        cal.setTime(now);
        java.sql.Date sqlDate = new java.sql.Date(cal.getTimeInMillis());
        order.setUpdateDate(sqlDate);
        
        order.setPaymentTime(now);
        order.setStartTime(now);  // 假设支付后立即开始充电
        
        // 设置order_year_month字段，格式为yyyy-MM
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
        order.setOrderYearMonth(sdf.format(now));

        // 计算预计结束时间（当前时间+充电分钟数）
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(now);
        calendar.add(Calendar.MINUTE, chargingMinutes);
        order.setEndTime(calendar.getTime());

        // 设置订单状态为"充电中"
        order.setStatus(OrderEntity.STATUS_CHARGING);

        // 设置支付方式为微信支付
        order.setPaymentMethod("WECHAT");
        order.setPayType("wxpay");

        // 设置充电桩信息 - 确保使用正确的eleCode
        order.setEleCode(eleCode);
        
        // 设置区域编码
        String regionCode = getRegionCodeByEleCode(eleCode);
        if (regionCode != null) {
            order.setRegionCode(regionCode);
        } else {
            // 如果找不到区域编码，记录警告但不阻止订单创建
            log.warn("未找到设备 {} 的区域编码，使用默认值", eleCode);
            order.setRegionCode("default");
        }

        // 设置用户ID（这里需要实际获取当前用户ID）
        order.setUserId("system_user"); // 替换为实际的用户ID获取逻辑

        // 保存订单
        chargingOrderService.save(order);

        return order;
    }
    
    /**
     * 根据电桩号获取区域编码
     */
    private String getRegionCodeByEleCode(String eleCode) {
        try {
            // 使用JdbcTemplate直接查询数据库
            String sql = "SELECT region_code FROM charging_pile WHERE ele_code = ? LIMIT 1";
            return jct.queryForObject(sql, String.class, eleCode);
        } catch (EmptyResultDataAccessException e) {
            log.warn("未找到电桩信息: eleCode={}", eleCode);
            return null;
        } catch (Exception e) {
            log.error("获取区域编码失败: eleCode={}", eleCode, e);
            return null;
        }
    }
    /**
     * 获取设备状态
     */
    private DeviceState getDeviceState(String iccid) {
        return deviceStates.computeIfAbsent(iccid, k -> new DeviceState());
    }
    /**
     * 计算实际充电金额（基于实际充电量）
     */
    private BigDecimal calculateActualAmount(BigDecimal chargingKwh, BigDecimal unitPrice) {
        if (chargingKwh != null && unitPrice != null) {
            return chargingKwh.multiply(unitPrice);
        }
        return BigDecimal.ZERO;
    }
    /**
     * 根据IMEI查找ICCID
     */
    private String findIccidByImei(String imei) {
        for (Map.Entry<String, DeviceConfig> entry : deviceConfigs.entrySet()) {
            if (entry.getValue().imei.equals(imei)) {
                return entry.getKey();
            }
        }
        return null;
    }

    /**
     * 处理心跳包 - 核心修复
     */
    private String handleHeartbeat(String iccid) {
        log.info("处理心跳包 - ICCID: {}", iccid);

        DeviceStatus status = deviceStatusMap.getOrDefault(iccid, DeviceStatus.UNKNOWN);

        if (status == DeviceStatus.UNKNOWN || status == DeviceStatus.EXPECT_HEARTBEAT) {
            deviceStatusMap.put(iccid, DeviceStatus.EXPECT_SELF_CHECK);
            log.info("设备 {} 心跳正常", iccid);

            // 关键修复2: 返回带服务端标记的响应
            return SERVER_TAG + "已接收到心跳包，请开始自检";
        }

        if (status == DeviceStatus.CHARGING || status == DeviceStatus.EXPECT_SELF_CHECK) {
            log.info("设备 {} 心跳正常（健康检查）", iccid);
            return SERVER_TAG + "心跳正常";
        }

        log.warn("异常状态收到心跳: {}", status);
        return SERVER_TAG + "ERROR|非预期心跳";
    }

    /**
     * 异步处理no load消息
     */
    private void handleNoLoadMessageAsync(String iccid) {
        CompletableFuture.runAsync(() -> {
            try {
                // 构造消息体
                JSONObject message = new JSONObject();
                message.put("device_id", iccid);
                message.put("status", "no load");
                
                // 调用MqttMessageListener212处理no load消息
                mqttMessageListener.handleNoLoadMessage(message.toJSONString());
            } catch (Exception e) {
                log.error("处理no load消息失败", e);
            }
        });
    }

    /**
     * 工作模式枚举
     */
    private enum WorkMode {
        AMOUNT_BASED,  // 模式一：按金额充电
        TIME_BASED     // 模式二：按时间充电
    }

    /**
     * 通过ICCID查找IMEI
     */
    public String findImeiByIccid(String iccid) {
        DeviceConfig config = deviceConfigs.get(iccid);
        return config != null ? config.imei : null;
    }

    /**
     * 设备状态类
     */
    private static class DeviceState {
        String imei;          // 关联的IMEI
        int amountCents;      // 金额（分）
        WorkMode workMode;    // 工作模式
        long lastHeartbeatTime; // 最后心跳时间（毫秒）
    }

    /**
     * 提取ICCID的方法
     */
    private String extractIccid(String topic, String payload) {
        // 如果主题是纯数字，直接作为ICCID
        if (topic != null && topic.matches("^\\d{15,20}$")) {
            return topic;
        }

        // 尝试从消息内容提取
        Matcher matcher = Pattern.compile("^\\d+").matcher(payload);
        if (matcher.find()) {
            return matcher.group();
        }

        log.error("无法提取ICCID | 主题: {}, 内容: {}", topic, payload);
        return "UNKNOWN";
    }

    /**
     * 设备配置类
     */
    private static class DeviceConfig {
        String imei;         // 关联的IMEI
        WorkMode workMode;    // 工作模式
    }
}